const { Summary, Project } = require('../db');
const XLSX = require('xlsx');
const { dateFormat } = require('../utils');

const outer = () => {};

// 项目数据导出
outer.exportData = async (options) => {
  const { projectId, workName} = options;
  const project = await Project.findOne({ projectId });
  console.log(project);

  if(!project) {
    return { 'success': false, 'msg': '项目信息不正确'};
  }
  console.log(project, 'projects');

  const projectName = project.projectName;

  // 设置表格基本信息
  const conf = {
    // name: 'test',
    name: `${projectName}-${workName}`, // 表格名称
  };

  conf.cols = [
    {
      caption: '序号',
      type: 'number',
    },
    {
      caption: '开始时间',
      type: 'string',
    },
    {
      caption: '结束时间',
      type: 'string',
    },
    {
      caption: '行走压力',
      type: 'string',
    },
    {
      caption: '旋转压力',
      type: 'string',
    },
    {
      caption: '泥浆压力',
      type: 'string',
    },
    {
      caption: '转速',
      type: 'number',
    },
  ];

  conf.rows = [
    ['1', '1', '1', '1', '1', '1', '1'],
    ['1', '1', '1', '1', '1', '1', '1'],
    ['1', '1', '1', '1', '1', '1', '1'],
    ['1', '1', '1', '1', '1', '1', '1'],
    ['1', '1', '1', '1', '1', '1', '1'],
  ];

  // const data = await Summary.find({ projectId, workName }).sort({ date: 1}).catch(err => {} );

  // for(const item of data) {
  //   const {
  //   //   date,
  //     currentCLIndex,
  //   //   deepLength,
  //   //   runningForce,
  //   //   rotateForce,
  //   //   landForce,
  //   //   rotateSpeed,
  //   } = item;
  //   // 当前钻杆数求取平均值
  //   // const summary = {
  //   //   runningForce: 0,
  //   //   rotateForce: 0,
  //   //   landForce: 0,
  //   //   rotateSpeed: 0,
  //   // };
  //   const list = data.filter(item => item.currentCLIndex === currentCLIndex);
  //   const listLen = list.length;
  //   const averageSpeed = list.reduce((a, b) => {
  //     return a + b.rotateSpeed;
  //   });
  //   // for(const o of list) {
  //   //     const {
  //   //         runningForce,
  //   //     rotateForce,
  //   //     landForce,
  //   //     rotateSpeed,
  //   //     } = o
  //   //     summary.runningForce += runningForce
  //   //     summary.rotateForce += rotateForce
  //   //     summary.landForce += landForce
  //   //     summary.rotateSpeed + = rotateSpeed
  //   // }
  //   conf.rows.push([
  //     currentCLIndex,
  //     list[0].date,
  //     list[listLen - 1].date,
  //     `${list[0].runningForce} - ${list[listLen - 1].runningForce}`,
  //     `${list[0].rotateForce} - ${list[listLen - 1].rotateForce}`,
  //     `${list[0].landForce} - ${list[listLen - 1].landForce}`,
  //     parseInt(averageSpeed / listLen),
  //   ]);
  // }


  const result = excelExport.execute(conf);
  const filename = `attachment;filename=${encodeURIComponent(`${projectName}-${workName}`)}.xlsx`;
  return {result, filename};
  // const bufferData = new Buffer(result, 'binary');
  // console.log(bufferData, '----');
  // return bufferData;

  // fs.writeFile('../../public/test.xlsx', result, 'binary', function(err, res) {
  //   if(err) {
  //     console.log(err);
  //   }
  //   console.log(res, 'res');
  //   return '/test.xlsx';
  // });
};

outer.exportData = async (params) => {
  const { projectId, workName } = params;

  if(!projectId) {
    return { 'success': false, 'msg': '请选择项目信息' };
  }

  if(!workName) {
    return { 'success': false, 'msg': '请选择作业名称' };
  }

  // 查询项目信息
  const project = await Project.findOne({ projectId }, { projectName: 1, len: 1});

  // 查询数据
  const data = await Summary.find({
    projectId,
    workName,
  }, {
    'deepLength': 1,
    'runningForce': 1,
    'rotateForce': 1,
    'landForce': 1,
    'rotateSpeed': 1,
    'createdAt': 1,
  }).sort({ 'deepLength': 1});
  console.log(data.length, 'length');

  // 表头配置
  const titles = ['序号', '日期', '开始时间', '结束时间', '每根钻杆扩孔时间', '行走压力(bar)', '旋转扭矩(KN·m)', '泥浆压力(bar)', '动力头转速(R/min)'];
  const xlsData = [titles];
  const list = [];
  const { projectName, len } = project;
  for(const item of data) {
    const { deepLength, runningForce, rotateForce, landForce, rotateSpeed } = item;
    const index = parseInt(Number(deepLength) / Number(len));
    const time = new Date(item.createdAt).getTime();

    if(list[index]) {
      const record = list[index];
      if(time < record[2]) {
        record[2] = time;
      }
      if(time > record[3]) {
        record[3] = time;
      }
      if(runningForce > record[5]) {
        record[5] = runningForce;
      }
      if(rotateForce > record[6]) {
        record[6] = rotateForce;
      }
      if(landForce > record[7]) {
        record[7] = landForce;
      }
      if(rotateSpeed > record[8]) {
        record[8] = rotateSpeed;
      }
    } else {
      list[index] = [index, time, time, time, 0, runningForce,rotateForce,landForce, rotateSpeed ];
    }
  }

  // 处理时间信息
  const filterData = list
    .filter(item => item && item.length > 0)
    .map(item => {
      const diff = (item[3] - item[2]) / 1000;
      let hour = parseInt(diff / 3600);
      let minute = parseInt(diff % 3600 / 60);
      let second = parseInt(diff % 3600 % 60);
      hour = hour < 10 ? `0${hour}` : hour;
      minute = minute < 10 ? `0${minute}` : minute;
      second = second < 10 ? `0${second}` : second;
      item[1] = dateFormat(item[1]);
      item[2] = dateFormat(item[2], 'Y-m-d H:i:s');
      item[3] = dateFormat(item[3], 'Y-m-d H:i:s');
      item[4] = `${hour}:${minute}:${second}`;
      return item;
    });

  const arr = xlsData.concat(filterData);

  let result, mimeType, filename;
  //json转excel
  let sheet = XLSX.utils.aoa_to_sheet(arr);
  //excel转node文件流
  result = outer.sheetToBuffer(sheet);
  mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  filename = `attachment;filename=${encodeURIComponent(`${projectName}-${workName}`)}.xlsx`;
  return {result, mimeType, filename};
};

outer.sheetToBuffer = (sheet, sheetName)=> {
  sheetName = sheetName || 'sheet1';
  let workbook = {
    SheetNames: [sheetName],
    Sheets: {},
  };
  workbook.Sheets[sheetName] = sheet;
  // 生成excel的配置项
  let wopts = {
    bookType: 'xlsx', // 要生成的文件类型
    type: 'buffer',
  };
  let wbout = XLSX.write(workbook, wopts);
  return wbout;
};

// outer.exportData({ projectId: '123456', workName: '扩孔450'});

module.exports = outer;